package com.isoftstone.bank.controller;


import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.bank.entity.BOrg;
import com.isoftstone.bank.service.IMerchantService;
import com.isoftstone.bank.service.impl.BOrgService;
import com.isoftstone.common.Page;
import com.isoftstone.common.Tidings;
import com.isoftstone.common.entity.SysUser;
import com.isoftstone.common.service.ISysUserRoleService;
import com.isoftstone.common.service.ISysUserService;
import com.isoftstone.merchant.entity.city.City;
import com.isoftstone.merchant.entity.merchant.Merchant;
import com.isoftstone.merchant.service.city.CityService;
import com.isoftstone.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wlj on 2017/11/29.
 *
 * 银行端，商户模块
 */
@Controller
public class MerchantController extends BaseController {
    @Autowired
    private BOrgService orgService;
    @Autowired
    IMerchantService mMerchantService;

    @Autowired
    private BOrgService service;
    @Autowired
    CityService cityService;

    @Autowired
    ISysUserService sysUserService;


    @Autowired
    ISysUserRoleService sysUserRoleService;
    /**
     * 进入商户管理页面
     * @param page
     * @return
     */
    @RequiresPermissions("bms-menu.002.001")
    @RequestMapping("/bank/merchant")
    public ModelAndView toMerchantPage(Page page){
        ModelAndView md = new ModelAndView();
        md.setViewName("/bank/merchant/merchant_list");
        return md;
    }

    /**
     * 条件查询商户
     * @param page
     * @return
     */
    @RequestMapping("/bank/getMerchantList")
    @ResponseBody
    public Object getMerchantlist(Page page) {
        Tidings<Map> tidings = new Tidings<Map>();
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            PageData pd = this.getPageData();
            if(pd.get("orgId") != null && !StringUtils.isEmpty(pd.get("orgId")+"")){
                BOrg org = service.selectByPrimaryKey(Long.parseLong(pd.get("orgId").toString()));
                pd.put("orgLevel",org.getOrgLevel());
            }
            page.setPd(pd);
            this.getSession().setAttribute("orgLevel",pd.get("orgLevel"));
            this.getSession().setAttribute("orgId",pd.get("orgId"));
            this.getSession().setAttribute("corpCode",pd.get("corpCode"));
            this.getSession().setAttribute("corpName",pd.get("corpName"));
            this.getSession().setAttribute("status",pd.get("status"));
            List<Merchant> merchantList = mMerchantService.getMerchantlistPage(page);

            List<City> cityList  = new ArrayList<City>();
            City city = new City();
            city.setCityCode("");
            city.setCityName(Const.SELECTALL);
            cityList.add(city);
            cityList.addAll(cityService.getPaymentCityList());

            map.put("cityList",cityList);
            map.put("merchantList",merchantList);

            tidings.setT(map);
            tidings.setPage(page);

            tidings.setStatus(Const.SUCCESS);
        } catch (Exception e) {
            tidings.setStatus(Const.ERROR);
            e.printStackTrace();
        }
        return tidings;
    }

    @RequestMapping("/bank/exportToExcel")
    public ModelAndView exportToExcel(Page page) {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("商户编号");
        titles.add("商户名称");
        titles.add("所属机构");
        titles.add("联系人");
        titles.add("联系电话");
        titles.add("状态");
        titles.add("地址");
        titles.add("对公账户");
        dataMap.put("titles", titles);
        List<PageData> subList = new ArrayList<PageData>();
        PageData pd = this.getPageData();

        pd.put("orgLevel",this.getSession().getAttribute("orgLevel"));
        pd.put("orgId",this.getSession().getAttribute("orgId"));
        pd.put("corpCode",this.getSession().getAttribute("endDate"));
        pd.put("corpName",this.getSession().getAttribute("beginDate"));
        pd.put("status",this.getSession().getAttribute("payStatus"));
        page.setPd(pd);
        List<Merchant> merchantList = new ArrayList<Merchant>();
        try {
            page.setShowCount(999999999);//mark
             merchantList = mMerchantService.getMerchantlistPage(page);
            for (Merchant merchant : merchantList) {
                PageData subpd = new PageData();
                subpd.put("var1", merchant.getCorpCode());
                subpd.put("var2", merchant.getCorpName());
                subpd.put("var3", merchant.getOrgName());//机构
                subpd.put("var4", merchant.getLinkMan());
                subpd.put("var5", merchant.getLinkPhone());
                subpd.put("var6", merchant.getStatusName());
                subpd.put("var7", merchant.getAddr());
                subpd.put("var8", merchant.getCardNo());

                subList.add(subpd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataMap.put("varList", subList);
        dataMap.put("name", "商户Excel");
        dataMap.put("sheetName", "商户");
        ObjectExcelView oev = new ObjectExcelView();
        mv = new ModelAndView(oev, dataMap);
        return mv;
    }
    /**
     * 银行端禁用商户(次方法同样可以更新商户所有信息)
     */
    @RequestMapping("/bank/updateMerchant")
    @ResponseBody
    public Object updateMerchant(Merchant merchant){
        Tidings<String> tidings = null;
        try {
            tidings = this.mMerchantService.updateMerchant(merchant,this.getUser(),this.getRequest().getRemoteAddr());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }
    /**
     * 增或者更新
     */
    @RequestMapping("/bank/merchant/saveMerchant")
    @ResponseBody
    public Object addMerchant(@ModelAttribute("merchant") Merchant merchant) throws Exception {
        Tidings<String> tidings = new Tidings<String>();
        if(merchant.getCorpId() == null || "".equals(merchant.getCorpId()) ){
            tidings = this.mMerchantService.addMerchant(merchant,this.getUser(),this.getRequest().getRemoteAddr());
        }else{
            tidings = this.mMerchantService.updateMerchant(merchant,this.getUser(),this.getRequest().getRemoteAddr());
        }
        return tidings;
    }
    /**
     * 查询单个商户
     */
    @RequestMapping("/bank/getMerchantById")
    @ResponseBody
    public ModelAndView getMerchantById(String corpId){
        Tidings<Merchant> tidings = this.mMerchantService.getMerchantById(corpId);

        ModelAndView md = new ModelAndView();
        md.addObject("MERCHANT", JsonUtil.beanToJson(tidings));
        md.setViewName("/bank/merchant/merchant_info");

        return md;
    }


    @RequestMapping("/bank/merchant/uploadPicFile")
    @ResponseBody
    public String uploadPicture(@RequestParam("upload_file") MultipartFile multipartFile){
        String filePath = null;
        try {
            filePath = FileUpload.prodFileUploadByRandomFileName(multipartFile, PathUtil.getClasspath()+Const.FILEPATHIMG);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    @RequestMapping("/bank/merchant/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("upload_file") MultipartFile multipartFile){
        String filePath = null;
        try {
            filePath = FileUpload.prodFileUploadByRandomFileName(multipartFile, PathUtil.getClasspath()+Const.FILEPATHFILE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
    @RequestMapping("/bank/merchant/removeFile")
    @ResponseBody
    public Object removeImg(String fileName,String fileType){
        Tidings<String> tiding = new Tidings<>();
        File file = null;
        if(null != fileType && fileType.equals(Const.FILETYPE_FILE)){
            file = new File(PathUtil.getClasspath()+Const.FILEPATHFILE+fileName);
        }else if (null != fileType && fileType.equals(Const.FILETYPE_PICTURE)){
            file = new File(PathUtil.getClasspath()+Const.FILEPATHIMG+fileName);
        }
        if(file == null){
            tiding.setStatus(Const.ERROR);
            return tiding;
        }
        file.getAbsoluteFile().delete();
        tiding.setStatus(Const.SUCCESS);
        return tiding;
    }

    @RequestMapping("bank/downloadPic")
    public  void  downLoadFile(String filePath) throws IOException {
         byte[] data = FileUtil.toByteArray2(filePath);
        this.getResponse().reset();
        this.getResponse().setHeader("Content-Disposition", "attachment; filename=aaaa");
        this.getResponse().addHeader("Content-Length", "" + data.length);
        this.getResponse().setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(this.getResponse().getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        this.getResponse().flushBuffer();
    }

    /**
     * 进入商户管理员管理页面
     * @param page
     * @return
     */
    @RequiresPermissions("bms-menu.002.002")
    @RequestMapping("/bank/merchantManager")
    public ModelAndView toMerchantManagerPage(Page page){
        ModelAndView md = new ModelAndView();
        md.setViewName("/bank/merchant/merchant_manager_list");
        return md;
    }
    /**
     *获取所有商户
     */
    @RequestMapping("/bank/getAllMerchantList")
    @ResponseBody
    public Object getAllMerchantList() throws Exception {
        Tidings<List<Merchant>> tidings = new Tidings<List<Merchant>>();
        PageData pd = this.getPageData();
        List<TreeNode> orgList = new ArrayList<TreeNode>();
        if("".equals(pd.get("orgId")) || null == pd.get("orgId")){
            orgList = orgService.selectOrgTreeNodeByOrgId(Long.valueOf(this.getUser().getCorpId()));
        }else{
            orgList = orgService.selectOrgTreeNodeByOrgId(Long.valueOf(pd.get("orgId").toString()));
        }
        if(null != orgList){
            String orgIds = this.getChildrenId(orgList);
            if(null != orgIds && !"".equals(orgIds)){
                String tem = orgIds.toString();
                if(",".equals(tem.substring(tem.length()-1,tem.length()))){
                    pd.put("orgIds", tem.substring(0,tem.length()-1));
                }else{
                    pd.put("orgIds",  orgIds);
                }
            }
        }

        tidings = this.mMerchantService.getAllMerchantList(pd);

        return tidings;
    }

    /**
     * 新增商户管理员
     * @param sysUser
     * @return
     */
    @RequestMapping("/bank/merchant/saveMercantManager")
    @ResponseBody
    public Object saveMercantManager(SysUser sysUser) throws Exception {
        String userid = UuidUtil.getNumFormatUUID();
        sysUser.setUserid(userid);
        Tidings<String> tidings = sysUserService.saveMercantManager(sysUser,this.getRequest(),this.getUser());
//        sysUserRoleService.updateUserRoleByUserIdAndRoleId(userid, sysUser.getRoleid());//更新用户与角色对应关系

        return tidings;
    }
    private String getChildrenId(List<TreeNode> children){
        String str = "";
        if (children != null){
            for(int i=0;i<children.size();i++){
                TreeNode temNode = children.get(i);
                str = str + temNode.getId() +",";
                if(temNode.getChildren() != null ){
                    str = str + getChildrenId(temNode.getChildren()) ;
                }
            }
        }
        return str;
    }
}
